package com.kangjia.config;

import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class DataBaseConfig {

	@Value("${db.url}")
	private String url;
	@Value("${db.username}")
	private String username;
	@Value("${db.password}")
	private String password;
	@Value("${db.driverclass}")
	private String driverclass;
	@Value("${db.initialSize}")
	private Integer initialSize;
	@Value("${db.minIdle}")
	private Integer minIdle;
	@Value("${db.maxActive}")
	private Integer maxActive;
	@Value("${db.maxWait}")
	private Long maxWait;
	@Value("${db.timeBetweenEvictionRunsMillis}")
	private Long timeBetweenEvictionRunsMillis;
	@Value("${db.minEvictableIdleTimeMillis}")
	private Long minEvictableIdleTimeMillis;
	@Value("${db.validationQuery}")
	private String validationQuery;
	@Value("${db.testWhileIdle}")
	private Boolean testWhileIdle;
	@Value("${db.testOnBorrow}")
	private Boolean testOnBorrow;
	@Value("${db.testOnReturn}")
	private Boolean testOnReturn;
	@Value("${db.poolPreparedStatements}")
	private Boolean poolPreparedStatements;
	@Value("${db.maxPoolPreparedStatementPerConnectionSize}")
	private Integer maxPoolPreparedStatementPerConnectionSize;
	@Value("${db.filters}")
	private String filters;

	@Bean(initMethod = "init", destroyMethod = "close")
	public DruidDataSource druidDataSource() {
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setUrl(url);
		druidDataSource.setUsername(username);
		druidDataSource.setPassword(password);
		druidDataSource.setDriverClassName(driverclass);
		druidDataSource.setInitialSize(initialSize);
		druidDataSource.setMaxActive(maxActive);
		druidDataSource.setMinIdle(minIdle);
		druidDataSource.setMaxWait(maxWait);
		druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		druidDataSource.setValidationQuery(validationQuery);
		druidDataSource.setTestOnBorrow(testOnBorrow);
		druidDataSource.setTestOnReturn(testOnReturn);
		druidDataSource.setTestWhileIdle(testWhileIdle);
		druidDataSource.setPoolPreparedStatements(poolPreparedStatements);
		druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
		try {
			druidDataSource.setFilters(filters);
		} catch (SQLException e) {
			throw new RuntimeException("SQLException", e);
		}
		return druidDataSource;
	}
}
